package com.yisoo.ubag.app.manager;



import com.alibaba.fastjson.JSONObject;
import com.yisoo.ubag.app.to.WxLoginResponseTo;
import com.yisoo.ubag.app.util.HttpUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.HashMap;
import java.util.Map;

@Service("wxApiManager")
public class WxApiManager {

//    yisoo.wx.appid = wxb0ab44b7f76e1c82
//    yisoo.wx.secret = 5d40f06256c0285e7728222186cf21ed
    @Value("${yisoo.wx.appid}")
    private String appid;
    @Value("${yisoo.wx.secret}")
    private String secret;
//GET https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
    public WxLoginResponseTo runLogin(String code){
        String host = "https://api.weixin.qq.com";
        String path = "/sns/jscode2session";
        Map<String, String> headers = new HashMap<>();
        Map<String, String> param = new HashMap<>();
        param.put("appid", appid);
        param.put("secret", secret);
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");
        try {
            HttpResponse response = HttpUtils.doGet(host, path, "GET", headers, param);
//            System.out.println(response.toString());
            String res = EntityUtils.toString(response.getEntity());
            WxLoginResponseTo wxLoginResponseTo = JSONObject.parseObject(res, WxLoginResponseTo.class);
            return wxLoginResponseTo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new WxLoginResponseTo(null,null,null,-100,"网路异常");
    }


}
